查看原文
其他

Perl学习13之路径获取模块: Cwd、FindBin和File::Basename

pythonic生物人 pythonic生物人 2022-09-11

"pythonic生物人"的第20篇分享



摘要

详细介绍perl中路径获取模块:Cwd、FindBin和File::Basename模块

目录

1、FindBin
$Bin
$Script

2、Cwd 

getcwd() cwd() fastcwd() fastgetcwd()
abs_path

3、File::Basename

4、参考资料



正文开始啦



1、FindBin

  • $Bin

返回被执行的脚本绝对路径;

  • $Script

返回被执行的脚本名称;




2、Cwd 

  • getcwd() cwd() fastcwd() fastgetcwd()

Cwd 模块默认载入以上四函数,返回执行脚本的路径;

例如您在/home/test 下执行了perl hello.pl,则以上四函数均返回/home/test;

  • abs_path

需要自己载入,即 use Cwd qw(abs_path);

abs_path($file) 返回绝对路径/$file

例如,

#!/usr/bin/perluse strict;use warnings;
use FindBin qw($Bin $Script $RealBin $RealScript);#use Cwd qw(abs_path);use Cwd;#默认导入函数 cwd(), getcwd(), fastcwd()及fastgetcwd()use Cwd qw(abs_path);

print "$Bin\n";#$Bin 返回脚本的绝对路径print "$Script\n";#$Script返回脚本名字print "$RealBin\n";print "$RealScript\n";
#getcwd() cwd() fastcwd() fastgetcwd() 获取当前"执行程序"的路径my $dir = getcwd();my $dir1 = cwd();my $dir2 = fastcwd();my $dir3 = fastgetcwd();print "\n";print "$dir\n";print "$dir1\n";print "$dir2\n";print "$dir3\n";
print "\n";my $abs_path = abs_path($Script);#返回$Script绝对路径/$Scriptprint "$abs_path\n";


执行结果

cd /home/study/perl/#执行脚本的路径
perl test/findbin.pl
/home/study/perl/test#被执行脚本所在路径
findbin.pl
/home/study/perl/test
findbin.pl
/home/study/perl/#返回执行脚本的路径
/home/study/perl/
/home/study/perl/
/home/study/perl/
/home/study/perl/findbin.pl#返回执行脚本的路径/被执行脚本


3、File::Basename

File::Basename模块拆分路径
例如,path.pl
#! /usr/bin/perluse strict;use warnings;
use File::Basename;my $path = $ARGV[0];my($filename, $dirs, $suffix) = fileparse($path,qr/\.[^.]*/);#以上分别为文件名,文件绝对路径,文件后缀名print"$filename\t$dirs\t$suffix\n";
my $filename1=basename($path);#默认返回带后缀文件名my $dirname1=dirname($path);#返回绝对路径print "$filename1\t$dirname1\n";
perl path.pl /home/study/max.pl
max     /home/study/    .pl
max.pl  /home/study 


4、参考资料
https://perldoc.perl.org/Cwd.htmlhttps://perldoc.perl.org/FindBin.htmlhttps://perldoc.perl.org/File/Basename.html
同系列文章

Perl学习01之标量数据
Perl学习02数组和哈希使用
Perl学习03之流程控制结构
Perl学习04之IO及文件读写
Perl学习05之正则表达式
Perl学习06之一行式操作
Perl学习07之自增(++)自减(--)
Perl学习08之子程序
Perl学习09之文件目录操作
Perl学习10之perl模块详解(一)
Perl学习11之perl模块详解(二)
Perl学习12之defined undef使用


持续更新,欢迎您"关注"、"在看"、"分享"


您可能也对以下帖子感兴趣

文章有问题?点此查看未经处理的缓存